# 分析日志   发送邮件 (定时任务)

import os
from myfirstproj import settings
import logging
import os
import smtplib
from myfirstproj import settings

from email.mime.text import MIMEText

log_file = 'statistics.log'
logger = logging.getLogger('django')


def log_analyse():
    log_file_path = os.path.join(settings.BASE_DIR, log_file)
    if not os.path.exists(log_file_path):
        # print('日志不存在')# log一下
        logger.info('log file not exist')
        return

    # 发邮件 要发送的统计结果
    # result = {'path1':[],'path2':[]....}
    # [{},{}]
    result = {}
    with open(log_file_path, 'r', encoding='utf8') as f:
        for line in f:
            # print('---->',line,end='')
            line = line.strip()
            line_dict = eval(line)
            print(line_dict)

            # 记录数据  key:value([次数,最少min,最多max,总耗时])
            # xxx接口1  平均耗时xx  最高耗时xx 最少耗时xx  出现次数
            # xxx接口2  平均耗时xx  最高耗时xx 最少耗时xx  出现次数

            # 如果 line_dict['path'] 出现过, result count +1
            # 如果 line_dict['path'] 没出现过, result count = 1
            # result[count]  记录接口访问次数
            # result[min] = 记录最少耗时
            # result[max] = 最长耗时
            # result[avg]平均耗时xx= 总耗时/次数
            key = line_dict['path']
            if key in result:
                result[key][0] += 1  # 第零位标识次数
                if line_dict['used_time'] < result[key][1]:
                    result[key][1] = line_dict['used_time']
                if line_dict['used_time'] > result[key][1]:
                    result[key][2] = line_dict['used_time']
                result[key][3] += line_dict['used_time']
            else:  # 第一次
                result[key] = ['次数', '最小值', '最大值', '总时间']
                result[key][0] = 1
                result[key][1] = line_dict['used_time']
                result[key][2] = line_dict['used_time']
                result[key][3] = line_dict['used_time']

        return result


def analyse():
    res = log_analyse()
    for key in res:
        res[key].append(res[key][3] / res[key][0])
    return res


def send_email():
    msg = MIMEText(repr(analyse()), "plain", "utf-8")
    # 发件人
    msg['FROM'] = "andy"
    # 主题
    msg['Subject'] = "【端口统计】"
    # 接收人
    receivers = ['lcqbug@qq.com', 'z1072202294@qq.com']
    server = smtplib.SMTP_SSL(settings.EMAIL_HOST, settings.EMAIL_PORT_SSL)
    # server = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT)
    server.set_debuglevel(1)
    server.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
    server.sendmail(settings.EMAIL_FROM, receivers, msg.as_string())
    server.close()


if __name__ == '__main__':
    # res = analyse()
    # print(res)
    send_email()
